﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Model.DI;
using Microsoft.Extensions.Logging;
using Model.EntityModel.Auth;
using Model.EntityModel.SysModel;
using Model.ResultModel;
using Repository.IRepository.ISysRepository;
using Service.IService.ISysService;
using Group = Model.EntityModel.Auth.Group;

namespace Service.Service.SysService
{
    /// <summary>
    /// 部门与组别关联服务实现
    /// </summary>
    [AppService(ServiceType = typeof(IDeptGroupService), ServiceLifetime = LifeTime.Scoped)]
    public class DeptGroupService : IDeptGroupService
    {
        private readonly IDeptGroupRepository _deptGroupRepo;
        private readonly IGroupRepository _groupRepo;
        private readonly IDeptRepository _deptRepo;
        private readonly ILogger<DeptGroupService> _logger;

        public DeptGroupService(
            IDeptGroupRepository deptGroupRepo,
            IGroupRepository groupRepo,
            IDeptRepository deptRepo,
            ILogger<DeptGroupService> logger)
        {
            _deptGroupRepo = deptGroupRepo;
            _groupRepo = groupRepo;
            _deptRepo = deptRepo;
            _logger = logger;
        }

     

        public List<DeptGroup> GetDeptGroups(string deptId)
        {
            return _deptGroupRepo.GetDeptGroups(deptId);
        }

        public bool AddGroupsToDept(string deptId, List<string> groupIds)
        {
            // 验证部门存在性
            if (!_deptRepo.DeptExists(deptId))
            {
                throw new InvalidOperationException($"部门ID {deptId} 不存在");
            }

            // 验证组别有效性
            var validGroups = _groupRepo.GetGroupsByIds(groupIds);
            var invalidGroups = groupIds.Except(validGroups.Select(g => g.Id)).ToList();

            if (invalidGroups.Any())
            {
                throw new InvalidOperationException($"包含无效的组别ID: {string.Join(",", invalidGroups)}");
            }

            return _deptGroupRepo.AddGroupsToDept(deptId, groupIds);
        }

        public bool RemoveGroupsFromDept(string deptId, List<string> groupIds)
        {
            return _deptGroupRepo.RemoveGroupsFromDept(deptId, groupIds);
        }

        public bool UpdateDeptGroupStatus(string relationId, string isActive)
        {
            return _deptGroupRepo.UpdateDeptGroupStatus(relationId, isActive);
        }

        public bool DeptGroupExists(string deptId, string groupId)
        {
            return _deptGroupRepo.DeptGroupExists(deptId, groupId);
        }
        public List<Group> GetAvailableGroupsForDept(string deptId)
        {
            return _deptGroupRepo.GetAvailableGroupsForDept(deptId);
        }

        List<Dept> IDeptGroupService.GetDeptGroups(string deptId)
        {
            throw new NotImplementedException();
        }
    }
}